package org.example.auth.service.impl;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.example.auth.config.AuthParamsConfig;
import org.example.auth.config.Constant;
import org.example.auth.contract.request.LoginRequest;
import org.example.auth.model.entity.User;
import org.example.auth.model.entity.UserRole;
import org.example.auth.service.LoginService;
import org.example.auth.service.RoleService;
import org.example.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthParamsConfig authParamsConfig;

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public String login(LoginRequest request) {
        User user = userService.login(request.getLoginName(), request.getPassword());
        UserRole defaultRole = roleService.getDefaultRoleByUserId(user.getId());
        return generateToken(user.getId(),defaultRole);
    }


    private String generateToken(Long id, UserRole userRole) {
        SecretKey key = generalKey();
        log.info("生成密钥：{}", key);
        Map<String, Object> map = new HashMap<>();
        if (userRole != null) {
            map.put(Constant.USER_ID, userRole.getUserId().toString());
            map.put(Constant.ROLE_ID, userRole.getRoleId().toString());
        }
        return Jwts.builder()
                .setSubject(id.toString())
                .addClaims(map)
                // 设置过期时间为1天，token 有效期24小时
                .setExpiration(getNextDay())
                // SECRET_KEY 自定义的密钥
                .signWith(SignatureAlgorithm.HS256, authParamsConfig.getJwtSecret())
                .compact();
    }

    private SecretKey generalKey() {
        // 本地的密码解码
        byte[] encodedKey = Base64.decodeBase64(authParamsConfig.getJwtSecret());
        // 根据给定的字节数组使用AES加密算法构造一个密钥
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    private Date getNextDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return calendar.getTime();
    }
}
